#include <audio_decoder.h>
audio_decoder::audio_decoder(const char* codec_name,AVCodecParameters* codecpar)
{
    int ret = 0;
    m_codec_name = codec_name;
     //opts_dec
    m_dec = avcodec_find_decoder_by_name(codec_name);
    if (!m_dec) {
        av_log(NULL, AV_LOG_FATAL, "Necessary decoder not found %s\n", codec_name); 
        return ;      
    }
    m_dec_ctx = avcodec_alloc_context3(m_dec);
    avcodec_parameters_to_context(m_dec_ctx, codecpar);
    ret = avcodec_open2(m_dec_ctx, m_dec, NULL);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n"); 
        m_open_success = false;       
    }else{
        m_open_success = true;
    }    

    int channels  = av_get_channel_layout_nb_channels(m_dec_ctx->channel_layout);

    printf("channels :%d\n",channels);
}

audio_decoder::~audio_decoder()
{
}

int  audio_decoder::decode(AVPacket* pkt,AVFrame* frame,int eof,int& got,int* finished) 
{
    int ret = 0;
    got = 0;    
    int error;
    ret = avcodec_send_packet(m_dec_ctx, pkt);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Error while sending a packet to the decoder\n");
        return ret;
    }

    /* Receive one frame from the decoder. */
    error = avcodec_receive_frame(m_dec_ctx, frame);
    /* If the decoder asks for more data to be able to decode a frame,
     * return indicating that no data is present. */
    if (error == AVERROR(EAGAIN)) {
        error = 0;
        return error;
    /* If the end of the input file is reached, stop decoding. */
    } else if (error == AVERROR_EOF) {
        *finished = 1;
        error = 0;
        return 0;
    } else if (error < 0) {
         char errbuf[128];
        av_strerror(ret, errbuf, sizeof(errbuf));
        fprintf(stderr, "Could not decode frame (error '%s')\n",errbuf);
        return error;
    /* Default case: Return decoded data. */
    } else {
        got = 1;
        return 0;
    }
    return 0;
}
int  audio_decoder::encode(const AVFrame*  frame, AVPacket* packet,int& got,int* finished) 
{
    return 0;
}
AVMediaType audio_decoder::get_codec_type() const 
{
    return AVMEDIA_TYPE_AUDIO;
}
